<?php

namespace App\Providers;

use DateTime;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 监听记录 执行的 sql
        Event::listen(function (QueryExecuted $event) {
            $sql = str_replace("%", "--", $event->sql); // 原生 sql 带 % Y%-m%-d，先替换 %，会冲突 vsprintf
            $sql = str_replace("?", "% s", $sql);
            foreach ($event->bindings as $i => $binding) {
                if ($binding instanceof DateTime) {
                    $event->bindings [$i] = $binding->format("Y-m-d H:i:s");
                } else if (is_numeric($binding)) {
                    $event->bindings [$i] = $binding;
                } else {
                    $event->bindings [$i] = "'$binding'";
                }
            }
            $log = vsprintf($sql, $event->bindings);
            $log = str_replace("--", "%", $log);
            Log::channel('sql')->info("===========================================sql start========================================");
            Log::channel('sql')->info('Sql', ['Sql' => $log, 'RunTime' => $event->time . 'ms']);
            Log::channel('sql')->info("===========================================sql end==========================================");
        });
    }
}
